// pages/cart/cart.js
import {Dialog} from "../../utils/util";
import {getSetting,chooseAddress,openSetting,showToast} from "../../utils/asyncWx"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList:[],
    total:0,
    selectNum:0,
    allPrice:0,
    allChecked:false,
    address: {},
  },
  checkboxChange(e){
    const {id:goods_id} = e.currentTarget.dataset;
    const [checked] = e.detail.value
    const newCartList =  this.data.cartList.map(item=>{
      if(item.goods_id===goods_id){
        return {
          ...item,
          isChecked:checked ? true:false,
        }
      } 
      return item;
    })
    
    this.setData({
      cartList:newCartList,
      allPrice:this.calcPrice(newCartList),
      allChecked:this.isAllChecked(newCartList),
    })
    wx.setStorageSync('hy1_cart_list', newCartList);
  },
  allCheckboxChange(e){
    const [checked] = e.detail.value;
    console.log(checked);
    const newCartList =  this.data.cartList.map(item=>{
        return {
          ...item,
          isChecked:checked ? true:false,
        }
    })
    this.setData({
      cartList:newCartList,
      allPrice:this.calcPrice(newCartList),
      allChecked:this.isAllChecked(newCartList),
    })
    wx.setStorageSync('hy1_cart_list', newCartList);
  },
  isAllChecked(arr){
   const checkList = arr.filter(item=>item.isChecked);
   return checkList.length === arr.length;
  },
  cartInit(){
    const cartList = wx.getStorageSync('hy1_cart_list')||[];
    this.setData({
      cartList,
      allPrice:this.calcPrice(cartList),
      allChecked:this.isAllChecked(cartList),
    })
  },
  calcPrice(arrar){
    const newArr = arrar.filter(item=>item.isChecked);
    return newArr.reduce((prev,next)=>{
      return prev += (next.count * next.goods_price)
    },0)
  },
  async sub_goods(e){
    console.log(e.currentTarget.dataset);
    const {id:goods_id} = e.currentTarget.dataset;
    const curent_goods = this.data.cartList.find(item=>item.goods_id==goods_id);
    if(curent_goods.count >1)curent_goods.count --;
    if(curent_goods.count ==1){
      try {
        const data = await Dialog({ title:"提示",content:"你确定要删除吗？"});
        this.del_goods(goods_id);
      } catch (error) {
        console.log(error);
      }
    
    }
    console.log(this.data.cartList);
    this.setData({
      cartList:this.data.cartList,
      allPrice:this.calcPrice(this.data.cartList)
    })
    wx.setStorageSync('hy1_cart_list', this.data.cartList);
  },
  add_goods(e){
    const {id:goods_id} = e.currentTarget.dataset;
    const curent_goods = this.data.cartList.find(item=>item.goods_id==goods_id);
    curent_goods.count ++;
    this.setData({
      cartList:this.data.cartList,
      allPrice:this.calcPrice(this.data.cartList)
    })
    wx.setStorageSync('hy1_cart_list', this.data.cartList);
  },
  del_goods(goods_id){
    const index = this.data.cartList.findIndex(item=>item.goods_id==goods_id);
    this.data.cartList.splice(index,1);
  },
  async handleChooseAddress() {
    try {
      // 1 获取权限状态
      const res1 = await getSetting()
      // 调用上面这个方法的时候,获取用户曾经是否设置过获取收货地址的权限,
      // 如果点击了确定. authSetting scopeAddress 的true-----直接获取收货地址;
      // 如果用户从来没有调用过  scope的值是undefined  -----没有获取
      // 如果点击了取消 ---scope的值就false
      //  1:诱导用户去打开授权设置的界面----opensetting----- 可以给获取收货地址授权;

      //表示看看用户有没有获取收货地址的权限;
      const scopeAddress = res1.authSetting['scope.address']
      if (scopeAddress === false) {
        //打开权限设置的页面; ---让用户重新设置权限;
        await openSetting()
      }

      // 调用收货地址的api
      let address = await chooseAddress()
      console.log(address)
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;

      //存到缓存中
      wx.setStorageSync("address", address);

    } catch (error) {
      console.log('你干哈呢')
    }
  },
  async handlePay() {
    //判断收货地址;
    const {
      address,
      total
    } = this.data;
    if (!address.userName) {
      await showToast({
        title: '您还没有选择收货地址'
      })
      return;
    }
    //判断用户有没有选择商品
    if (total === 0) {
      await showToast({
        title: '您还没有选购商品'
      })
      return;
    }
    //跳转到支付页面;
    wx.navigateTo({
      url: '/pages/pay/pay'
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onload执行了');
    this.cartInit();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onShow执行了');
    this.cartInit();
    const address = wx.getStorageSync("address");
        //获取缓存中购物车 的数据;
    this.setData({
      address
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})